<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>getBoundingClientRect</title>
  <style>
    * {
      margin: 0;
      padding: 0;
    }

    body {
      height: 3000px;
      width: 3000px;
    }

    .box {
      width: 100px;
      height: 100px;
      background-color: red;
      margin-top: 300px;
      margin-left: 300px;
    }
  </style>
</head>

<body>
  <div class="box"></div>
</body>

</html>

<script>
  let oBox = document.querySelector(".box");
  // Element.getBoundingClientRect()  方法返回元素的大小及其相对于视口的位置。
  console.log(oBox.getBoundingClientRect());

  // 判断元素是否在可视区域
  function checkInView(dom) {
    const { top, left, bottom, right } = dom.getBoundingClientRect()
    // console.log(top, left, bottom, right)
    // console.log(window.innerHeight, window.innerWidth)
    return top >= 0 &&
      left >= 0 &&
      bottom <= (window.innerHeight || document.documentElement.clientHeight) &&
      right <= (window.innerWidth || document.documentElement.clientWidth)
  }

  window.onscroll = function () {
    // box完整出现在视口里才会输出true，否则为false
    console.log(checkInView(oBox))
  }

</script>